// 结局收集册系统
class EndingGallery {
    constructor() {
        this.unlockedEndings = new Set();
        this.endingCategories = {
            scientific: ['scientific_light', 'quantum_observer', 'time_theorist'],
            exploration: ['multiverse_explorer', 'dimension_walker', 'reality_architect'],
            guardian: ['eternal_guardian', 'world_protector', 'safety_guardian'],
            fusion: ['fusion_being', 'cosmic_consciousness', 'enlightened_one'],
            conquest: ['multiverse_conqueror', 'reality_destroyer'],
            romance: ['interdimensional_romance', 'ai_companion'],
            mystery: ['paradox_creator', 'accidental_traveler'],
            unity: ['unifier', 'eternal_scholar']
        };
        
        this.endingDescriptions = {
            scientific_light: {
                title: '科学之光',
                description: '你选择了科学和理性的道路，成为了推动人类文明进步的科学家。',
                unlockHint: '选择科学路线的所有分支'
            },
            quantum_observer: {
                title: '量子观察者',
                description: '你掌握了观察和理解量子现象的能力，成为现实的见证者。',
                unlockHint: '在多个章节中选择观察和分析'
            },
            // ... 更多结局描述
        };
        
        this.init();
    }
    
    init() {
        this.loadEndingData();
        this.setupEndingDisplay();
        console.log('✓ 结局收集册已初始化');
    }
    
    setupEndingDisplay() {
        // 监听结局解锁事件
        window.addEventListener('endingReached', (e) => {
            this.unlockEnding(e.detail.endingId);
        });
        
        // 创建结局展示界面
        this.createEndingGalleryUI();
    }
    
    createEndingGalleryUI() {
        // 查找或创建结局收集册界面
        let endingGallery = document.getElementById('endingGalleryScreen');
        if (!endingGallery) {
            endingGallery = document.createElement('div');
            endingGallery.id = 'endingGalleryScreen';
            endingGallery.className = 'screen';
            
            endingGallery.innerHTML = `
                <div class="ending-gallery-container">
                    <h2 data-i18n="endingGallery">结局收集册</h2>
                    <div class="ending-stats">
                        <span id="endingProgressText">已解锁: 0/20</span>
                        <div class="ending-progress-bar">
                            <div class="ending-progress-fill" id="endingProgressFill"></div>
                        </div>
                    </div>
                    <div class="ending-categories" id="endingCategories"></div>
                    <div class="ending-grid" id="endingGrid"></div>
                    <button class="back-btn" data-i18n="back">返回</button>
                </div>
            `;
            
            document.body.appendChild(endingGallery);
        }
        
        this.updateEndingDisplay();
    }
    
    unlockEnding(endingId) {
        if (!this.unlockedEndings.has(endingId)) {
            this.unlockedEndings.add(endingId);
            this.saveEndingData();
            this.showEndingUnlockNotification(endingId);
            this.updateEndingDisplay();
            
            // 触发成就检查
            this.checkEndingAchievements();
        }
    }
    
    updateEndingDisplay() {
        const progressText = document.getElementById('endingProgressText');
        const progressFill = document.getElementById('endingProgressFill');
        const endingGrid = document.getElementById('endingGrid');
        
        if (progressText && progressFill) {
            const totalEndings = 20;
            const unlockedCount = this.unlockedEndings.size;
            const percentage = (unlockedCount / totalEndings) * 100;
            
            progressText.textContent = `已解锁: ${unlockedCount}/${totalEndings}`;
            progressFill.style.width = `${percentage}%`;
        }
        
        if (endingGrid) {
            this.renderEndingGrid(endingGrid);
        }
    }
    
    renderEndingGrid(container) {
        container.innerHTML = '';
        
        Object.entries(this.endingCategories).forEach(([category, endings]) => {
            const categoryDiv = document.createElement('div');
            categoryDiv.className = 'ending-category';
            
            const categoryTitle = document.createElement('h3');
            categoryTitle.textContent = this.getCategoryName(category);
            categoryTitle.className = 'category-title';
            categoryDiv.appendChild(categoryTitle);
            
            const endingsContainer = document.createElement('div');
            endingsContainer.className = 'category-endings';
            
            endings.forEach(endingId => {
                const endingCard = this.createEndingCard(endingId);
                endingsContainer.appendChild(endingCard);
            });
            
            categoryDiv.appendChild(endingsContainer);
            container.appendChild(categoryDiv);
        });
    }
    
    createEndingCard(endingId) {
        const card = document.createElement('div');
        const isUnlocked = this.unlockedEndings.has(endingId);
        
        card.className = `ending-card ${isUnlocked ? 'unlocked' : 'locked'}`;
        
        if (isUnlocked) {
            const ending = this.endingDescriptions[endingId];
            if (ending) {
                card.innerHTML = `
                    <div class="ending-icon">🌟</div>
                    <h4 class="ending-title">${ending.title}</h4>
                    <p class="ending-description">${ending.description}</p>
                    <div class="ending-date">解锁时间: ${this.getUnlockDate(endingId)}</div>
                `;
            }
        } else {
            card.innerHTML = `
                <div class="ending-icon">❓</div>
                <h4 class="ending-title">???</h4>
                <p class="ending-hint">${this.getEndingHint(endingId)}</p>
            `;
        }
        
        return card;
    }
    
    getCategoryName(category) {
        const names = {
            scientific: '科学路线',
            exploration: '探索路线',
            guardian: '守护路线',
            fusion: '融合路线',
            conquest: '征服路线',
            romance: '浪漫路线',
            mystery: '神秘路线',
            unity: '统一路线'
        };
        return names[category] || category;
    }
    
    getEndingHint(endingId) {
        const ending = this.endingDescriptions[endingId];
        return ending ? ending.unlockHint : '探索不同的选择分支';
    }
    
    getUnlockDate(endingId) {
        const endingData = this.loadEndingData();
        if (endingData.unlockDates && endingData.unlockDates[endingId]) {
            return new Date(endingData.unlockDates[endingId]).toLocaleDateString();
        }
        return '未知';
    }
    
    showEndingUnlockNotification(endingId) {
        const ending = this.endingDescriptions[endingId];
        if (!ending) return;
        
        // 创建结局解锁通知
        const notification = document.createElement('div');
        notification.className = 'ending-unlock-notification';
        notification.innerHTML = `
            <div class="notification-content">
                <div class="notification-icon">🌟</div>
                <div class="notification-text">
                    <h3>新结局解锁!</h3>
                    <p>${ending.title}</p>
                </div>
            </div>
        `;
        
        // 添加样式
        Object.assign(notification.style, {
            position: 'fixed',
            top: '50%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            background: 'linear-gradient(135deg, rgba(0, 212, 255, 0.9), rgba(78, 205, 196, 0.9))',
            borderRadius: '16px',
            padding: '24px',
            color: 'white',
            fontWeight: '600',
            zIndex: '10001',
            animation: 'endingUnlock 3s ease-out',
            backdropFilter: 'blur(20px)',
            border: '1px solid rgba(255, 255, 255, 0.3)',
            boxShadow: '0 8px 32px rgba(0, 0, 0, 0.3)'
        });
        
        document.body.appendChild(notification);
        
        // 自动移除
        setTimeout(() => {
            if (notification.parentNode) {
                notification.style.animation = 'fadeOut 0.5s ease-out';
                setTimeout(() => {
                    notification.parentNode.removeChild(notification);
                }, 500);
            }
        }, 3000);
    }
    
    checkEndingAchievements() {
        const unlockedCount = this.unlockedEndings.size;
        
        if (window.achievementSystem) {
            if (unlockedCount >= 1) {
                window.achievementSystem.unlock('first_ending');
            }
            if (unlockedCount >= 5) {
                window.achievementSystem.unlock('ending_collector');
            }
            if (unlockedCount >= 10) {
                window.achievementSystem.unlock('ending_enthusiast');
            }
            if (unlockedCount >= 20) {
                window.achievementSystem.unlock('ending_master');
            }
        }
    }
    
    // 数据持久化
    saveEndingData() {
        const data = {
            unlockedEndings: Array.from(this.unlockedEndings),
            unlockDates: this.getUnlockDates(),
            timestamp: Date.now()
        };
        
        localStorage.setItem('timeEcho_endings', JSON.stringify(data));
    }
    
    loadEndingData() {
        const saved = localStorage.getItem('timeEcho_endings');
        if (saved) {
            try {
                const data = JSON.parse(saved);
                this.unlockedEndings = new Set(data.unlockedEndings || []);
                return data;
            } catch (error) {
                console.warn('结局数据加载失败:', error);
            }
        }
        return { unlockedEndings: [], unlockDates: {} };
    }
    
    getUnlockDates() {
        const data = this.loadEndingData();
        return data.unlockDates || {};
    }
    
    getEndingStats() {
        return {
            total: 20,
            unlocked: this.unlockedEndings.size,
            percentage: Math.round((this.unlockedEndings.size / 20) * 100),
            categories: Object.keys(this.endingCategories).map(category => ({
                name: category,
                total: this.endingCategories[category].length,
                unlocked: this.endingCategories[category].filter(ending => 
                    this.unlockedEndings.has(ending)).length
            }))
        };
    }
}

// 创建全局实例
window.endingGallery = new EndingGallery();

// 添加动画样式
const endingAnimationStyle = document.createElement('style');
endingAnimationStyle.textContent = `
    @keyframes endingUnlock {
        0% { opacity: 0; transform: translate(-50%, -50%) scale(0.5); }
        50% { opacity: 1; transform: translate(-50%, -50%) scale(1.1); }
        100% { opacity: 1; transform: translate(-50%, -50%) scale(1); }
    }
    
    @keyframes fadeOut {
        from { opacity: 1; }
        to { opacity: 0; }
    }
`;
document.head.appendChild(endingAnimationStyle);